<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>DW抽取管理</title>
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <script src="/style/public/publicStyle.js"></script>
    <style type="text/css">
        .layui-table-tool-panel li .layui-form-checkbox[lay-skin=primary] {
            /* width: 100%; */
            padding-left: 28px;
        }

        .layui-table-tool-panel li {
            line-height: 30px;
            -webkit-transition: .5s all;
            transition: .5s all;
            padding-left: 10px;
            padding-right: 47px;
        }

        td .layui-form-select {
            margin-top: -10px;
            margin-left: -15px;
            margin-right: -15px;
        }

        .layui-table-cell {
            overflow: visible !important;
        }

        .layui-table-view .layui-table th {
            overflow: hidden;
        }

        .layui-table-click {
            background-color: #def0f5;
        }
    </style>
</head>

<body>
<!--表格-->
<div class="weadmin-body">
    <div class="layui-row">
        <table class="layui-hide" id="tableDataList" lay-filter="mainTableFilter"></table>
    </div>
</div>

<script type="text/html" id="standField">
    <select name="euType" lay-filter="euType">
        <option value="STRING">字符串</option>
        <option value="NUMBER">数值型</option>
        <option value="BYTE">二进制</option>
        <option value="DATE">日期</option>
        <option value="TIMESTAMP">时间戳</option>
    </select>
</script>
<!--表格操作-->
<script type="text/html" id="op">
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">配置</a>
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="createTb">建表</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
</script>

<script type="text/html" id="toolbarDemo">
    <input class="text" style="height:35px;width:257px;" name="" id="hiddenFilter" placeholder="根据表名过滤"/>
</script>

<div class="layui-row" id="tableForm" style="display:none;">
    <div class="layui-col-md12">
        <input type="hidden" name="idTaskOds"/>
        <div class="layui-form-item">
            <!--<form class="layui-form layui-from-pane" id="formId" style="margin-top:20px" lay-filter="tableForm">
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <label class="layui-form-label">DW表名</label>
                        <div class="layui-input-block">
                            <input class="layui-input" id="idTb" name="idTb" id="idTb"/>
                            <input type="hidden" class="layui-input" id="idTbOld" name="idTb" id="idTbOld"/>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <label class="layui-form-label">DW描述</label>
                        <div class="layui-input-block">
                            <input class="layui-input" name="na" id="na"/>
                            <input type="hidden" name="tbTar">
                            <input type="hidden" name="desEvent">
                            <input type="hidden" name="naTaskOds">
                            <input type="hidden" id="idTaskOds" name="idTaskOds">
                        </div>
                    </div>
                </div>
            </form>-->
        </div>
        <div class="layui-form-item">
            <div class="layui-form-item">
                <div class="layui-row">
                    <form class="layui-form layui-from-pane" id="formId" style="margin-top:20px" lay-filter="tableForm">
                        <div class="layui-col-md6">
                            <label class="layui-form-label">DW表名</label>
                            <div class="layui-input-block">
                                <input class="layui-input" name="cdTb" id="cdTb"/>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <label class="layui-form-label">DW描述</label>
                            <div class="layui-input-block">
                                <input class="layui-input" name="na" id="na"/>
                                <input type="hidden" name="tbTar">
                                <input type="hidden" name="desEvent">
                                <input type="hidden" name="naTaskOds">
                                <input type="hidden" id="idTaskOds" name="idTaskOds">
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <label class="layui-form-label">时间条件列</label>
                        <div class="layui-input-block">
                            <select id="dateFidSelect"
                                    style="width: 100%; height: 38px;border-color: #efefef;font-size: medium;padding: 7px;"></select>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-input-block">
                            <a type="button" id="saveFid" onclick="saveFid()" class="layui-btn layui-btn-normal"
                               style="float: right;margin-right: 15px;">
                                保存
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-row">
            <div class="layui-col-md12">
                <table class="layui-table" style="width: 912px;margin-left: 15px;display: none">
                    <colgroup>
                        <col width="150">
                        <col width="200">
                        <col width="200">
                    </colgroup>
                    <thead>
                    <tr>
                        <th>ODS列名</th>
                        <th>DW字段(维度、度量、日期)</th>
                        <th>DW字段(时分秒)</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr style="display: none">
                        <th>11111111</th>
                        <th>222222222</th>
                        <th id="defulyTh">
                            <form class="layui-form layui-from-pane" id="formId111"
                                  style=" overflow: visible !important;height: 8px;margin-top: -19px;"
                                  lay-filter="tableForm111">
                                <select name="modules" lay-filter="mainSelectIdFilter" lay-verify="required"
                                        lay-search="" id="mainSelectId">
                                    <option value="">直接选择或搜索选择</option>
                                </select>
                            </form>
                        </th>
                    </tr>
                    </tbody>
                </table>
                <table id="fldTable" class="layui-table" style="width: 912px;margin-left: 15px;">
                    <colgroup>
                        <col width="150">
                        <col width="200">
                        <col width="200">
                    </colgroup>
                    <thead>
                    <tr>
                        <th>ODS列名</th>
                        <th>DW字段(维度、度量、日期)</th>
                        <th>DW字段(时分秒)</th>
                    </tr>
                    </thead>
                    <tbody id="fildLIst">
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

</div>
<div class="layui-row" id="tableForm2" style="display:none;">
    <div class="layui-col-md12">
        <input type="hidden" name="idTaskOds"/>
        <div class="layui-form-item">
            <form class="layui-form layui-from-pane" id="formId3" style="margin-top:20px" lay-filter="tableForm11">
                <div class="layui-row">
                    <div class="layui-col-md8">
                        <label class="layui-form-label">DW表名</label>
                        <div class="layui-input-block">
                            <input class="layui-input " id="idTbDDL" name="cd"/>
                            <input type="hidden" id="oldCdTb" name="cd"/>
                            <input type="hidden" id="idTaskOds2" name="idTaskOds">
                        </div>
                    </div>
                    <!-- <div class="layui-col-md3">
                         <div class="layui-input-block">
                             <a type="button" id="execTypes" onclick="showExecTypesSql(this)"
                                class="layui-btn layui-btn-normal usrCreate"
                                style="margin-left:-59px;text-align: right; margin-right: 29px;">使用修改语句</a>
                         </div>
                     </div>-->
                    <div class="layui-col-md4">
                        <div class="layui-input-block">
                            <a type="button" id="execSql" onclick="execSql()"
                               class="layui-btn layui-btn-normal"
                               style="margin-left:-59px;text-align: right; margin-right: 29px;">执行</a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
        <!-- <div class="layui-form-item">
             <div class="layui-row">
                 <div class="layui-col-md12">
                     <div class="layui-card" id="execSqlCreate">
                         <div class="layui-card-header">创建语句</div>
                         <div class="layui-card-body">

                         </div>
                     </div>
                     <div class="layui-card" id="execSqlModify" style="display: none">
                         <div class="layui-card-header">修改语句</div>
                         <div class="layui-card-body">

                         </div>
                     </div>
                     <br/>
                 </div>
             </div>
         </div>-->
    </div>
</div>

</body>

<script>
    var currPage;
    var indexLay;
    layui.use(['util', 'laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element'], function () {
        var util = layui.util;
        var laydate = layui.laydate //日期
            , laypage = layui.laypage //分页
            , layer = layui.layer //弹层
            , table = layui.table //表格
            , carousel = layui.carousel //轮播
            , upload = layui.upload //上传
            , element = layui.element //元素操作
            , form = layui.form;
        var logintoken = null;
        getSharreTieba_LoginToken();
        table.render({
            elem: '#tableDataList'
            , even: false //开启隔行背景
            , cellMinWidth: 80
            , toolbar: '#toolbarDemo'
            , defaultToolbar: []
            , url: global_visit_url_prefix + '/etl/etlTaskDW/findByPage'
            , cols: [[
                , {field: 'idTaskOds', title: 'ID', hide: true}
                , {field: 'naTaskOds', title: 'ODS名称'}
                , {field: 'desEvent', title: 'ODS事件'}
                , {field: 'tbTar', title: 'ODS表名', hide: true}
                , {field: 'cdTb', title: 'DW表ID', hide: true}
                , {field: 'cdTb', title: 'DW表名'}
                , {field: 'na', title: 'DW名称'}
                , {field: 'dimTotal', title: '已配置列数量'}
                , {fixed: 'right', title: '操作', align: 'center', toolbar: '#op'}
            ]]
            , page: true
            , done: function (rest, curr, count) {
                currPage = curr;
            }
        });

        $("body").on("keypress", "#hiddenFilter", function (event) {
            var content = $(this).val();
            if (event.keyCode == '13') {
                //执行重载
                table.reload('tableDataList', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , where: {
                        filter: content //在表格中进行搜索
                    }
                });
                $("#hiddenFilter").val(content);
            }
        });


        /*table.reload("tableFidList", {data: []});*/
//监听行工具事件
        table.on('tool()', function (obj) { //注：tool 是工具条事件名，mainTableFilter 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
                , layEvent = obj.event; //获得 lay-event 对应的值
            if (layEvent == 'edit') {
                indexLay = layer.open({
                    //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                    type: 1,
                    title: "编辑DW抽取配置",
                    area: ['950px', '600px'],
                    content: $("#tableForm")//引用的弹出层的页面层的方式加载修改界面表单
                });
                //动态向表传递赋值可以参看文章进行修改界面的更新前数据的显示，当然也是异步请求的要数据的修改数据的获取
                setFormValue(obj, null);
                setFormValue(obj, data);
                fidlistMapper(data);
                /* tableReload("tableFidList");*/
                /*getTables(data.idDbSou)*/
            } else if (layEvent == 'createTb') {
                $.ajax({
                    url: '/etl/etlTaskDW/createTable',
                    type: 'get',
                    dataType: 'json',
                    data: {'idTaskOds': data.idTaskOds},
                    contentType: 'application/json;charset=UTF-8',
                    success: function (data1) {
                        layer.alert(data1.msg);
                    }
                });
                /* layer.open({
                     //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                     type: 1,
                     title: "DW建表",
                     area: ['660px', '190px'],
                     content: $("#tableForm2")//引用的弹出层的页面层的方式加载修改界面表单
                 });
                 setFormValue2(obj, null);
                 setFormValue2(obj, data);
                 /!* showDDLSql();*!/*/
            } else if (layEvent == 'delete') {
                layer.confirm('确定要删除吗？', {
                    btn: ['确定', '取消'], //按钮
                }, function () {
                    layer.closeAll('dialog');
                    $.ajax({
                        type: "get",
                        url: "/etl/etlTaskDW/delete",
                        async: true,
                        data: {'idTaskOds': data.idTaskOds},
                        success: function (json) {
                            if (json.euStatus == 'SUCCESS') {
                                alert("删除成功!");
                                table.reload("tableDataList");
                            } else {
                                alert(json.data);
                            }

                        }
                    });
                });
            }
        });
        /*table.render({
            elem: '#tableFidList'
            , even: false //开启隔行背景
            , id: 'tableFidList'
            , url: global_visit_url_prefix + '/etl/etlTaskDW/findFids'
            , cols: [[
                , {field: 'odsFid', title: 'ODS列名', event: 'setSign', style: 'cursor: pointer;'}
                , {field: 'dwFid1', title: 'DW字段(维度、度量、日期)', event: 'setSign1', style: 'cursor: pointer;'}
                , {field: 'dwFid2', title: 'DW字段(时分秒))', event: 'setSign2', style: 'cursor: pointer;'}
            ]]
        });*/

        var getFidName = function (obj) {
            if (obj == undefined || obj == 'undefined' || obj == '') {
                return '';
            }

            return $(".layui-anim-upbit dd[lay-value= '" + obj + "']").html();
        }

        var fidlistMapper = function (data111) {
            $("#defulyTh").append($('#formId111'));
            $("#fildLIst").html("");
            $("#dateFidSelect").html("");
            $("#dateFidSelect").val("");
            $.ajax({
                url: global_visit_url_prefix + '/etl/etlTaskDW/findFids',
                type: 'get',
                dataType: 'json',
                data: {'idTaskOds': $("#idTaskOds").val(), 'idTb': $("#idTb").val()},
                contentType: 'application/json;charset=UTF-8',
                success: function (data1) {
                    if (data1.code == 1) {
                        alert(data1.msg);
                        return;
                    }

                    var data = data1.data; //提出返回数据中的data
                    if (data.mappers !== null) {
                        $.each(data.mappers, function (index, item) { //循环加入 data的元素
                            var fff1 = '';
                            var fff2 = '';
                            var fff3 = 1;
                            var fff4 = '<i style="border: 1px solid #cbcbcb; margin-right: 9px;" onclick="addColumn(this)" class="layui-icon layui-icon-addition"></i>';
                            if (item.dwFid1 != undefined && item.dwFid1 != '') {
                                fff1 = item.dwFid1
                            }

                            if (item.dwFid2 != undefined && item.dwFid2 != '') {
                                fff2 = item.dwFid2
                            }

                            if (item.odsFidType != undefined && item.odsFidType != '') {
                                fff3 = item.odsFidType
                                if (fff3 == 2) {
                                    fff4 = '<i style="border: 1px solid #cbcbcb; margin-right: 9px;" onclick="removeColumn(this)" class="layui-icon layui-icon-subtraction"></i>';
                                }
                            }

                            $("#fildLIst").append('<tr>' +
                                '<td lay-value="' + item.odsFid + '" lay-type="' + fff3 + '">'
                                /* + fff4*/
                                + item.odsFid
                                + '</td>' +
                                '<td lay-value="' + item.dwFid1 + '" onclick="editFild2(this,1)">' + getFidName(fff1) + '</td>' +
                                '<td lay-value="' + item.dwFid2 + '" onclick="editFild2(this,2)" >' + getFidName(fff2) + '</td>' +
                                '</tr>');
                        });
                    }
                    if (data.dateFids !== null) {
                        $.each(data.dateFids, function (index, item) { //循环加入 data的元素
                            $("#dateFidSelect").append('<option value="' + item + '">' + item + '</option>');
                        });
                    }
                    if (data111.dateColumn != undefined && data111.dateColumn != undefined && data111.dateColumn != '') {
                        $("#dateFidSelect").val(data111.dateColumn);
                    }
                }
            });
        }

        //监听弹出框表单提交，massage是修改界面的表单数据'submit(demo11),是修改按钮的绑定
        function setFormValue(obj, data) {
            if (data == null) {
                $("#formId")[0].reset();
            } else {
                form.val("tableForm", data);
            }
        }

        function setFormValue2(obj, data) {
            if (data == null) {
                $("#formId3")[0].reset();
            } else {
                form.val("tableForm11", data);
            }
        }


        $.ajax({
            url: '/etl/mdMedPubfld/findByModel',
            type: 'get',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            success: function (data1) {
                var data = data1.data; //提出返回数据中的data
                form.val("tableForm", data);
                if (data !== null) {
                    $.each(data, function (index, item) { //循环加入 data的元素
                        $("#mainSelectId").append('<option value="' + item.idPubfld + '">' + item.na + '(' + item.idPubfld + ')</option>');
                    });
                    form.render('select');
                }
            }
        });
    });
    var showDDLSql = function () {
        $("#execSqlModify .layui-card-body").html("");
        $("#execSqlCreate .layui-card-body").html("");

        $.ajax({
            url: global_visit_url_prefix + '/etl/etlTaskDW/gerTableDDL',
            type: 'get',
            dataType: 'json',
            data: {'idTb': $("#idTbDDL").val()},
            contentType: 'application/json;charset=UTF-8',
            success: function (data1) {
                if (data1.code == 1) {
                    alert(data1.msg);
                    return;
                }


                var strs = data1.data.createSQL.split(";"); //字符分割

                for (i = 0; i < strs.length; i++) {
                    $("#execSqlCreate .layui-card-body").append(strs[i] + "; <br/>")
                }

                if (data1.data.modifySQL != undefined && data1.data.modifySQL != undefined && data1.data.modifySQL != '') {
                    strs = data1.data.modifySQL.split(";"); //字符分割
                    for (i = 0; i < strs.length; i++) {
                        $("#execSqlModify .layui-card-body").append(strs[i] + "; <br/>")
                    }
                }

                /* $("#execSqlModify").html(data1.data.modifySQL);
                 /!*$("#execSqlCreate").html(data1.data.createSQL);*!/*/
            }
        });
    }

    var saveEdit = function () {
        $("#defulyTh").append($('#formId111'));
        var na = $('.layui-anim-upbit .layui-this').html();
        var sd = $('.layui-anim-upbit .layui-this').attr("lay-value")
        if (sd !== undefined && sd !== '') {
            $(".currEdit").html(na);
            $('.currEdit').attr("lay-value", sd);
        } else {
            $(".currEdit").html("");
            $('.currEdit').attr("lay-value", 'undefined');
        }
    }
    var addColumn = function (obj) {
        var jQuery = $(obj).parent();

        $(obj).parent().parent().after('<tr>' +
            '<td lay-value="' + jQuery.attr("lay-value") + '" lay-type="2">'
            + '<i style="border: 1px solid #cbcbcb; margin-right: 9px;" onclick="removeColumn(this)" class="layui-icon layui-icon-subtraction"></i>'
            + jQuery.attr("lay-value")
            + '</td>' +
            '<td lay-value="" onclick="editFild2(this,1)"></td>' +
            '<td lay-value="" onclick="editFild2(this,2)"></td>' +
            '</tr>');

    }

    var removeColumn = function (obj) {
        $(obj).parent().parent().detach();

    }

    var editFild2 = function (obj, index) {
        if (!$(obj).hasClass('currEdit')) {
            saveEdit();

            var oldSd = $(obj).attr("lay-value");
            if (oldSd !== undefined && oldSd !== 'undefined' && oldSd !== '') {
                $(".layui-anim-upbit dd[lay-value= '" + oldSd + "']").click();
            } else {
                $(".layui-select-tips").click();
                $(".layui-this").removeClass("layui-this");
            }

            $(".currEdit").removeClass("currEdit");
            $(obj).html("");
            $(obj).addClass("currEdit");
            $(obj).append($('#formId111'))
        }
    }

    var showExecTypesSql = function (obj) {
        if ($("#execTypes").hasClass("usrCreate")) {
            $("#execSqlModify").show();
            $("#execSqlCreate").hide();
            $("#execTypes").html('使用创建语句')
            $("#execTypes").removeClass("usrCreate")
        } else {
            $("#execSqlModify").hide();
            $("#execSqlCreate").show();
            $("#execTypes").html('使用修改语句')
            $("#execTypes").addClass("usrCreate")
        }
    }

    var execSql = function () {
        var idTb = $("#idTbDDL").val()
        if (idTb.substr(0, 3) != "DW_" && idTb.substr(0, 3) != "dw_") {
            alert("DW表名需要以[DW_]开头");
            return;
        }

        $.ajax({
            url: '/etl/etlTaskDW/createTable',
            type: 'get',
            dataType: 'json',
            data: {'idTaskOds': $("#idTaskOds2").val(), 'cdTb': idTb, 'oldCdTb': $("#oldCdTb").val()},
            contentType: 'application/json;charset=UTF-8',
            success: function (data1) {
                if (data1.euStatus == 'SUCCESS') {
                    alert('执行成功:' + data1.msg)
                    window.location.reload();
                } else {
                    alert('执行失败：' + data1.msg)
                }
            }
        });
    }

    var saveFid = function () {
        saveEdit();
        var idTb = $('#cdTb').val().toUpperCase();
        $('#cdTb').val(idTb);

        if (idTb.substr(0, 3) != "DW_" && idTb.substr(0, 3) != "dw_") {
            alert("DW表名需要以[DW_]开头");
            return;
        }

        var idTbOld = $('#idTbOld').val();
        var na = $('#na').val();
        var idTaskOds = $('#idTaskOds').val();
        var dateColumn = $('#dateFidSelect').val();

        if (idTb == undefined || idTb == 'undefined' || idTb == '') {
            alert("DW表名不能为空");
            return;
        }
        if (na == undefined || na == 'undefined' || na == '') {
            alert("DW描述不能为空");
            return;
        }
        if (dateColumn == undefined || dateColumn == 'undefined' || dateColumn == '') {
            alert("ODS时间条件列为空，ODS-DW将全表导入！");
        }

        var fiddata = {};
        fiddata.cdTb = idTb;
        fiddata.dateColumn = dateColumn;
        fiddata.idTbOld = idTbOld;
        fiddata.na = na;
        fiddata.idTaskOds = idTaskOds;
        fiddata.filds = [];

        var allowSave = true;

        $("#fildLIst").find("tr").each(function () {
            var odsFid = $(this).children('td:eq(0)').attr("lay-value")
            var odsFidType = $(this).children('td:eq(0)').attr("lay-type")
            var dwFid1 = $(this).children('td:eq(1)').attr("lay-value")
            var dwFid2 = $(this).children('td:eq(2)').attr("lay-value")
            if (odsFid == undefined || odsFid == 'undefined' || odsFid == '') {
                odsFid = null;
            }
            if (odsFidType == undefined || odsFidType == 'undefined' || odsFidType == '') {
                odsFidType = null;
            }
            if (dwFid1 == undefined || dwFid1 == 'undefined' || dwFid1 == '') {
                dwFid1 = null;
            }
            if (dwFid2 == undefined || dwFid2 == 'undefined' || dwFid2 == '') {
                dwFid2 = null;
            }

            if (odsFid != null && odsFid == dateColumn) {
                if (dwFid1 == null) {
                    alert(dateColumn + "对应的日期与时间维度不能为空");
                    allowSave = false;
                }
            }

            if (odsFid != null && (dwFid1 != null || dwFid2 != null)) {
                var one = {};
                one.odsFid = odsFid;
                one.odsFidType = odsFidType;
                one.dwFid1 = dwFid1;
                one.dwFid2 = dwFid2;
                fiddata.filds.push(one);
            }
        });

        if (!allowSave) {
            return;
        }

        $.ajax({
            url: '/etl/etlTaskDW/save',
            type: 'post',
            dataType: 'json',
            data: JSON.stringify(fiddata),
            contentType: 'application/json;charset=UTF-8',
            success: function (data1) {
                if (data1.code == 1) {
                    alert(data1.msg);
                    return;
                }
              //  window.location.reload();
                layui.table.reload("tableDataList", {page: {curr: currPage}});
                layui.layer.close(indexLay);
            }
        });
    }
</script>

</html>